<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2017-08-27
 * Time: 11:15
 */

namespace app\models;

use app\librarys\DbCacheUtility;
use app\librarys\Tools;
use CLogFileHandler;
use WxPayConfig;
use yii\helpers\Url;


//var_dump(__DIR__.'../librarys/wx_pay/lib/WxPay.Api.php');exit;
require_once '../librarys/wx_pay/lib/WxPay.Api.php';
require_once '../librarys/wx_pay/lib/WxPay.Config.php';
require_once '../librarys/wx_pay/lib/log.php';
//$logHandler = new CLogFileHandler("../web/logs/" . date('Y-m-d') . '.log');
//$log = \Log::Init($logHandler, 15);

class WxPay
{
//    public static function wxPayTest()
//    {
//        $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
//        $input = new \WxPayUnifiedOrder();
//        $input->SetBody("屏主支付");
////        $input->SetAttach("test");//附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用。
//        $input->SetOut_trade_no(WxPayConfig::MCHID . date("YmdHis")); //订单号
//        $input->SetTotal_fee("1"); // 支付金额
////        $input->SetTime_start(date("YmdHis"));
////        $input->SetTime_expire(date("YmdHis", time() + 600));
////        $input->SetGoods_tag("test");
//        $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
//        $input->SetTrade_type("APP");
//        $input->SetSpbill_create_ip($host);
//        $reuslt = \WxPayApi::unifiedOrder($input);
//        var_dump($reuslt['prepay_id']);
//        exit;
//    }


    /**
     * 广告红包支付
     * @param $ad_id
     * @return bool|\成功时返回，其他抛异常
     */
    public static function payAdCashGift($ad_id)
    {
        $sql = 'SELECT * FROM t_ad_cash_gift WHERE ad_id = :ad_id AND pay_status = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $item = DbCacheUtility::queryOne($cmd);

        if ($item == null) {
            $data = [
                'result_code'=>'fail',
                'message' => '广告不存在或者是不为未支付状态'
            ];
            return $data;
        }

        $amount = $item['one_cash'] * $item['count'] * 100;

        $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("广告红包支付");
        $input->SetAttach('3'); //1--平台入驻 2--特殊行业广告认证费用 3--广告红包费用支付
            $tt=Tools::db_uuid();
        $tt2 = substr($tt,0,32);
        $trade_out_id = str_replace('-','',$tt2);
        $input->SetOut_trade_no($trade_out_id); //订单号
        self::saveTempTrade_no($trade_out_id,$item['ad_id']);
//        $input->SetOut_trade_no(str_replace('-', '', $item['ad_id'])); //订单号
        $input->SetTotal_fee($amount); // 支付金额
//        $input->SetTotal_fee(2); // 支付金额
        $notify_url = $_SERVER['HTTP_HOST'] . '/wx-pay/pay-notify'; //支付成功回调地址
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("APP");
        $input->SetSpbill_create_ip($host);

        $result = \WxPayApi::unifiedOrder($input);
        return $result;
    }

    /***
     * 特殊行业广告认证信息支付(300yuan)
     */
    public static function payAdSpecial($ad_id, $amount = 300)
    {
        $sql = 'SELECT * FROM t_ad_special WHERE ad_id = :ad_id AND pay_status = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $item = DbCacheUtility::queryOne($cmd);

        if ($item == null) {
            if ($item == null) {
                $data = [
                    'result_code'=>'fail',
                    'message' => '广告不存在或者是不为未支付状态'
                ];
                return $data;
            }
        }

        $amount = $amount * 100;

        $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("特殊行业广告认证费用");
        $input->SetAttach('2'); //1--平台入驻 2--特殊行业广告认证费用 3--广告红包费用支付

//        $trade_out_id=Tools::db_uuid();
        $tt=Tools::db_uuid();
        $tt2 = substr($tt,0,32);
        $trade_out_id = str_replace('-','',$tt2);
        $input->SetOut_trade_no($trade_out_id); //订单号
        self::saveTempTrade_no($trade_out_id,$item['ad_id']);

//        $input->SetOut_trade_no(str_replace('-', '', $item['ad_id'])); //订单号
        $input->SetTotal_fee($amount); // 支付金额
//        $input->SetTotal_fee(3); // 支付金额
        $notify_url = $_SERVER['HTTP_HOST'] . '/wx-pay/pay-notify'; //支付成功回调地址
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("APP");
        $input->SetSpbill_create_ip($host);

        $result = \WxPayApi::unifiedOrder($input);
        return $result;
    }

    /**
     * 平台入驻支付
     * @param $merchant_id
     * @param int $month_sum
     * @return \成功时返回，其他抛异常
     */
    public static function payMerchantGroup($merchant_id, $month_sum = 12, $mount_amount = 5)
    {
        $sql = 'SELECT * FROM t_merchant WHERE id = :merchant_id ';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':merchant_id', $merchant_id);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            if ($item == null) {
                $data = [
                    'result_code' => 'fail',
                    'message' => '未找到商户信息'
                ];
                return $data;
            }
        }

        $amount = $mount_amount * $month_sum * 100;
        $host = isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
        $input = new \WxPayUnifiedOrder();
        $input->SetBody("平台入驻费用");
        $attach = [
            'type' => 1,
            'month_sum' => $month_sum,
            'merchant_id' => $merchant_id
        ];

        $input->SetAttach(json_encode($attach)); //1--平台入驻 2--特殊行业广告认证费用 3--广告红包费用支付
        $input->SetOut_trade_no(date('YmdHis') . Tools::getRandomString(8)); //订单号,生成虚拟的订单号，待回调生成真正的平台入驻单
//        $input->SetOut_trade_no(Tools::getRandomString(12));
        $input->SetTotal_fee($amount); // 支付金额
//        $input->SetTotal_fee(1); // 支付金额
        $notify_url = $_SERVER['HTTP_HOST'] . '/wx-pay/pay-merchant-group-notify'; //支付成功回调地址
//        file_put_contents('../web/logs/' . date('YmdHi') . 'payMerchantGroupurl.txt', $notify_url);
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type("APP");
        $input->SetSpbill_create_ip($host);

        $result = \WxPayApi::unifiedOrder($input);
        return $result;
    }


    /**
     * 回调广告红包现金支付修改
     * @param $data
     * @return bool
     */
    public static function modifyAdCashGiftPay($data)
    {
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();

        $result = false;
        try {
            $app_id = $data['appid'];
            $mch_id = $data['mch_id'];
            $nonce_str = $data['nonce_str'];
            $sign = $data['sign'];
            $result_code = $data['result_code'];
            $open_id = $data['openid'];
            $trade_type = $data['trade_type'];
            $bank_type = $data['bank_type'];
            $total_fee = $data['total_fee'];
            $cash_fee = $data['cash_fee'];
            $transaction_id = $data['transaction_id'];
            $time_end = $data['time_end'];
            $attach = $data['attach'];
            $trade_out_no = $data['out_trade_no'];

            $ad_id = self::getTempTrade_no($trade_out_no);
            file_put_contents('../web/logs/' . date('YmdHi') . 'gift.txt', $ad_id);

//            $ad_id = $data['out_trade_no'];

            $ad = Ad::getAdByIdReplace($ad_id);
            $amount = $ad['one_cash'] * $ad['count'];
            //修改个人领取红包金额的金额
            $platform_rake_fee_rate = \Yii::$app->params['platform_rake_fee_rate'];
            $platform_rake_fee = $amount * $platform_rake_fee_rate;

            $agent_rake_fee_rate = \Yii::$app->params['agent_rake_fee_rate'];
            $agent_rake_fee = $platform_rake_fee * $agent_rake_fee_rate;

            $agent_id = Agent::getAgentIdByMerchantId($ad['merchant_id']);
            if ($agent_id) {
                $sql = 'INSERT INTO t_agent_rake_fee(ad_id, agent_id, pay_mode, agent_rake_fee, agent_rake_fee_rate)
                        VALUES (:ad_id, :agent_id, 1, :agent_rake_fee, :agent_rake_fee_rate)';
                $cmd = \Yii::$app->db->createCommand($sql);
                $cmd->bindValue(':ad_id', $ad['ad_id']);
                $cmd->bindValue(':agent_id', $agent_id);
                $cmd->bindValue(':agent_rake_fee', $agent_rake_fee);
                $cmd->bindValue(':agent_rake_fee_rate', $agent_rake_fee_rate);

                DbCacheUtility::execute($cmd);

                $platform_rake_fee = $platform_rake_fee - $agent_rake_fee;
            }


            $sql = 'INSERT INTO t_platform_rake_fee(ad_id, pay_mode, platform_rake_fee, platform_rake_fee_rate) 
                    VALUES (:ad_id, 1, :platform_rake_fee, :platform_rake_fee_rate)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad['ad_id']);
            $cmd->bindValue(':platform_rake_fee', $platform_rake_fee);
            $cmd->bindValue(':platform_rake_fee_rate', $platform_rake_fee_rate);
            DbCacheUtility::execute($cmd);


            //修改用户领取红包的总金额
            $amount = $amount - $platform_rake_fee;
            if($agent_id){
                $amount = $amount - $agent_rake_fee;
            }
//            $sql = 'UPDATE t_ad_cash_gift SET pay_status = 1,one_cash =:one_cash,one_cash_old = :one_cash_old WHERE replace(ad_id,\'-\',\'\') = :ad_id';

            $sql = 'UPDATE t_ad_cash_gift SET pay_status = 1,one_cash =:one_cash,one_cash_old = :one_cash_old WHERE ad_id = :ad_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
            $cmd->bindValue(':one_cash', floor($amount / $ad['count']*100)/100);
            $cmd->bindValue(':one_cash_old', $ad['one_cash']);
            DbCacheUtility::execute($cmd);

//            $sql = 'UPDATE t_ad SET status = 40 WHERE replace(id,\'-\',\'\') = :id';

            $sql = 'UPDATE t_ad SET status = 40 WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $ad_id);
            DbCacheUtility::execute($cmd);

            $sql = 'INSERT INTO t_wx_pay_record (id,app_id,mch_id,nonce_str,sign,result_code,open_id,trade_type,bank_type,total_fee,cash_fee,transaction_id,bill_type,out_trade_no,time_end,attach)
                    VALUES (uuid(),:app_id,:mch_id,:nonce_str,:sign,:result_code,:open_id,:trade_type,:bank_type,:total_fee,:cash_fee,:transaction_id,3,:out_trade_no,:time_end,:attach)';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':app_id', $app_id);
            $cmd->bindValue(':mch_id', $mch_id);
            $cmd->bindValue(':nonce_str', $nonce_str);
            $cmd->bindValue(':sign', $sign);
            $cmd->bindValue(':result_code', $result_code);
            $cmd->bindValue(':open_id', $open_id);
            $cmd->bindValue(':trade_type', $trade_type);
            $cmd->bindValue(':bank_type', $bank_type);
            $cmd->bindValue(':total_fee', $total_fee / 100);
            $cmd->bindValue(':cash_fee', $cash_fee / 100);
            $cmd->bindValue(':transaction_id', $transaction_id);
            $cmd->bindValue(':out_trade_no', $ad_id);
            $cmd->bindValue(':time_end', $time_end);
            $cmd->bindValue(':attach', $attach);
            DbCacheUtility::execute($cmd);

            $sql = 'SELECT merchant_id FROM t_ad WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $ad_id);
            $merchant_id = DbCacheUtility::queryScalar($cmd);

            $sql = 'INSERT INTO t_merchant_pay_record(id,merchant_id,amount,pay_mode,type,origin_id)
                    VALUES(uuid(),:merchant_id,:amount,1,:type,:origin_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':amount', $total_fee / 100);
            $cmd->bindValue(':type', $attach);
            $cmd->bindValue(':origin_id', $ad_id);
            DbCacheUtility::execute($cmd);

            $transaction->commit();
            Merchant::setGiftPaySuccess($ad_id);

            $result = true;

            //云联惠积分赠送
            $out_id = Tools::db_uuid();

            Merchant::sendYLHPoint($out_id,$cash_fee,'屏主红包支付','屏主红包支付',$merchant_id);

        } catch (\Exception $e) {
            var_dump($e);exit;
            $transaction->rollBack();
        }

        return $result;
    }

    /**
     * 回调特殊行业广告认证费用支付
     * @param $data
     * @return bool
     */
    public static function modifyAdSpecialPay($data)
    {
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();

        $result = false;
        try {
            $app_id = $data['appid'];
            $mch_id = $data['mch_id'];
            $nonce_str = $data['nonce_str'];
            $sign = $data['sign'];
            $result_code = $data['result_code'];
            $open_id = $data['openid'];
            $trade_type = $data['trade_type'];
            $bank_type = $data['bank_type'];
            $total_fee = $data['total_fee'];
            $cash_fee = $data['cash_fee'];
            $transaction_id = $data['transaction_id'];
            $time_end = $data['time_end'];
            $attach = $data['attach'];
            $trade_out_no = $data['out_trade_no'];

            $ad_id = self::getTempTrade_no($trade_out_no);

//            $ad_id = $data['out_trade_no'];

            $sql = 'UPDATE t_ad_special SET pay_status = 1 WHERE replace(ad_id,\'-\',\'\') = :ad_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
            DbCacheUtility::execute($cmd);

            $sql = 'UPDATE t_ad SET status = 10 WHERE replace(id,\'-\',\'\') = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $ad_id);
            DbCacheUtility::execute($cmd);

            $sql = 'INSERT INTO t_wx_pay_record (id,app_id,mch_id,nonce_str,sign,result_code,open_id,trade_type,bank_type,total_fee,cash_fee,transaction_id,bill_type,out_trade_no,time_end,attach)
                    VALUES (uuid(),:app_id,:mch_id,:nonce_str,:sign,:result_code,:open_id,:trade_type,:bank_type,:total_fee,:cash_fee,:transaction_id,2,:out_trade_no,:time_end,:attach)';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':app_id', $app_id);
            $cmd->bindValue(':mch_id', $mch_id);
            $cmd->bindValue(':nonce_str', $nonce_str);
            $cmd->bindValue(':sign', $sign);
            $cmd->bindValue(':result_code', $result_code);
            $cmd->bindValue(':open_id', $open_id);
            $cmd->bindValue(':trade_type', $trade_type);
            $cmd->bindValue(':bank_type', $bank_type);
            $cmd->bindValue(':total_fee', $total_fee / 100);
            $cmd->bindValue(':cash_fee', $cash_fee / 100);
            $cmd->bindValue(':transaction_id', $transaction_id);
            $cmd->bindValue(':out_trade_no', $ad_id);
            $cmd->bindValue(':time_end', $time_end);
            $cmd->bindValue(':attach', $attach);
            DbCacheUtility::execute($cmd);

            $sql = 'SELECT merchant_id FROM t_ad WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $ad_id);
            $merchant_id = DbCacheUtility::queryScalar($cmd);

            $sql = 'INSERT INTO t_merchant_pay_record(id,merchant_id,amount,pay_mode,type,origin_id)
                    VALUES(uuid(),:merchant_id,:amount,1,:type,:origin_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':amount', $total_fee / 100);
            $cmd->bindValue(':type', $attach);
            $cmd->bindValue(':origin_id', $data['out_trade_no']);
            DbCacheUtility::execute($cmd);

            $transaction->commit();
            $result = true;

            //云联惠积分赠送
            $out_id = Tools::db_uuid();

            Merchant::sendYLHPoint($out_id,$cash_fee,'屏主特殊行业审核','屏主特殊行业审核',$merchant_id);

        } catch (\Exception $e) {
            $transaction->rollBack();
        }

        return $result;
    }


    /**
     *平台入驻支付回调
     * @param $data
     * @return bool
     */
    public static function modifyMerchantGroupPay($data)
    {
        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();

        $result = false;
        try {
            $app_id = $data['appid'];
            $mch_id = $data['mch_id'];
            $nonce_str = $data['nonce_str'];
            $sign = $data['sign'];
            $result_code = $data['result_code'];
            $open_id = $data['openid'];
            $trade_type = $data['trade_type'];
            $bank_type = $data['bank_type'];
            $total_fee = $data['total_fee'];
            $cash_fee = $data['cash_fee'];
            $transaction_id = $data['transaction_id'];
            $time_end = $data['time_end'];
//            $merchant_id = $data['out_trade_no'];
//            $month_sum = $data['attach'];

            $attach = Tools::ObjectToArray(json_decode($data['attach']));
            $month_sum = $attach['month_sum'];
            $merchant_id = $attach['merchant_id'];
            $type = $attach['type'];

            //修改商户平台
            $sql = 'UPDATE t_merchant SET rent_begin_datetime = IF(rent_begin_datetime IS NULL ,NOW(),rent_begin_datetime),
                        rent_end_datetime = IF(rent_end_datetime IS NULL ,date_add(now(),interval :month_sum MONTH),date_add(rent_end_datetime,interval :month_sum MONTH)),
                        rent_amount = :rent_amount
                    WHERE id = :merchant_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':month_sum', $month_sum);
            $cmd->bindValue(':rent_amount', $total_fee / 100);
            DbCacheUtility::execute($cmd);


            $sql = 'INSERT INTO t_wx_pay_record (id,app_id,mch_id,nonce_str,sign,result_code,open_id,trade_type,bank_type,total_fee,cash_fee,transaction_id,bill_type,out_trade_no,time_end,attach)
                    VALUES (uuid(),:app_id,:mch_id,:nonce_str,:sign,:result_code,:open_id,:trade_type,:bank_type,:total_fee,:cash_fee,:transaction_id,1,:out_trade_no,:time_end,:attach)';

            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':app_id', $app_id);
            $cmd->bindValue(':mch_id', $mch_id);
            $cmd->bindValue(':nonce_str', $nonce_str);
            $cmd->bindValue(':sign', $sign);
            $cmd->bindValue(':result_code', $result_code);
            $cmd->bindValue(':open_id', $open_id);
            $cmd->bindValue(':trade_type', $trade_type);
            $cmd->bindValue(':bank_type', $bank_type);
            $cmd->bindValue(':total_fee', $total_fee / 100);
            $cmd->bindValue(':cash_fee', $cash_fee / 100);
            $cmd->bindValue(':transaction_id', $transaction_id);
            $cmd->bindValue(':out_trade_no', $merchant_id);
            $cmd->bindValue(':time_end', $time_end);
            $cmd->bindValue(':attach', json_encode($attach));

            DbCacheUtility::execute($cmd);


            $sql = 'INSERT INTO t_merchant_pay_record(id,merchant_id,amount,pay_mode,type,origin_id)
                    VALUES(uuid(),:merchant_id,:amount,1,:type,:origin_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':amount', $total_fee / 100);
            $cmd->bindValue(':type', $type);
            $cmd->bindValue(':origin_id', $merchant_id);
            DbCacheUtility::execute($cmd);

            $transaction->commit();
            $result = true;

            //给屏主用户发送屏主积分
//            Merchant::sendYLHPoint($merchant_id,$cash_fee,'屏主平台入驻订单','phone','屏主平台入驻订单','token');
            $out_id = Tools::db_uuid();
            Merchant::sendYLHPoint($out_id,$cash_fee,'屏主平台入驻','屏主平台入驻',$merchant_id);
        } catch (\Exception $e) {
            $transaction->rollBack();
            file_put_contents('../web/logs/' . date('YmdHis') . 'pay-merchan-group-notift-error.txt', $e->getMessage());
        }

        return $result;
    }


    public static function toUrlParams($array)
    {
        $buff = "";
        foreach ($array as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");

        return $buff;
    }

    public static function makeSign($array)
    {

        //签名步骤一：按字典序排序参数
        ksort($array);
        $string = self::toUrlParams($array);

        //签名步骤二：在string后加入KEY
        $string = $string . "&key=" . WxPayConfig::KEY;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 存储外部订单号
     * @param $trade_no
     * @param $ad_id
     */
    public static function saveTempTrade_no($trade_no,$ad_id)
    {
        $sql = 'insert into t_temp_wx_trade_id(id,ad_id)VALUES (:id,:ad_id)';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $trade_no);
        $cmd->bindValue(':ad_id', $ad_id);
        DbCacheUtility::execute($cmd);
    }

    public static function getTempTrade_no($trade_no)
    {
        $sql = 'select ad_id from t_temp_wx_trade_id where id=:id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $trade_no);
        return  DbCacheUtility::queryScalar($cmd);
    }


}